<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}
session_start();
require_once '../config.php';

// 检查是否登录
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// 获取系统设置
$settings = getSettings();

$action = $_GET['action'] ?? '';
$product_id = $_GET['id'] ?? 0;

try {
    // 处理删除请求
    if ($action === 'delete' && $product_id > 0) {
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $_SESSION['success'] = '商品删除成功';
        header('Location: product_manage.php');
        exit;
    }

    // 处理添加/编辑请求
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // 状态切换
        if (isset($_POST['toggle_id'])) {
            $toggle_id = intval($_POST['toggle_id']);
            $stmt = $pdo->prepare("UPDATE products SET status = IF(status=1,0,1) WHERE id = ?");
            $stmt->execute([$toggle_id]);
            $_SESSION['success'] = '商品状态已切换';
            header('Location: product_manage.php');
            exit;
        }
        // 添加/编辑商品
        $id = $_POST['id'] ?? 0;
        $name = sanitize($_POST['name']);
        $description = sanitize($_POST['description']);
        $price = floatval($_POST['price']);
        if ($price < 0.01) {
            $_SESSION['error'] = '商品价格不能低于0.01元';
            header('Location: product_manage.php');
            exit;
        }
        $duration_type = sanitize($_POST['duration_type']);
        $duration_value = intval($_POST['duration_value']);
        $purchase_limit = isset($_POST['purchase_limit']) ? intval($_POST['purchase_limit']) : 0;
        // 新增商品自动分配排序
        if ($id > 0) {
            $sort_order = intval($_POST['sort_order']);
        } else {
            $stmt = $pdo->query("SELECT MAX(sort_order) AS max_sort FROM products");
            $max_sort = $stmt->fetchColumn();
            $sort_order = is_numeric($max_sort) ? ($max_sort + 1) : 0;
        }
        // 新增商品默认上架
        $status = 1;
        // 后端校验时长值
        $max_map = [
            'minute' => 59,
            'hour' => 23,
            'day' => 30,
            'week' => 4,
            'month' => 11,
            'season' => 3,
            'year' => 9999,
            'forever' => 0,
            '分钟' => 59,
            '小时' => 23,
            '天' => 30,
            '周' => 4,
            '月' => 11,
            '季' => 3,
            '年' => 9999,
            '永久' => 0
        ];
        $max_duration = $max_map[$duration_type] ?? 9999;
        if ($duration_type !== 'forever' && $duration_type !== '永久') {
            if ($duration_value < 1 || $duration_value > $max_duration) {
                $_SESSION['error'] = '时长值超出允许范围';
                header('Location: product_manage.php');
                exit;
            }
        }
        if ($id > 0) { // 编辑
            $stmt = $pdo->prepare("UPDATE products SET name=?, description=?, price=?, duration_type=?, duration_value=?, status=?, sort_order=?, purchase_limit=? WHERE id=?");
            $stmt->execute([$name, $description, $price, $duration_type, $duration_value, $status, $sort_order, $purchase_limit, $id]);
            $_SESSION['success'] = '商品更新成功';
        } else { // 添加
            $stmt = $pdo->prepare("INSERT INTO products (name, description, price, duration_type, duration_value, status, sort_order, purchase_limit) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $description, $price, $duration_type, $duration_value, $status, $sort_order, $purchase_limit]);
            $_SESSION['success'] = '商品添加成功';
        }
        header('Location: product_manage.php');
        exit;
    }

    // PHP部分，处理?action=next_sort请求，返回下一个排序值
    if (isset($_GET['action']) && $_GET['action'] === 'next_sort') {
        $stmt = $pdo->query("SELECT MAX(sort_order) AS max_sort FROM products");
        $max_sort = $stmt->fetchColumn();
        $next_sort = is_numeric($max_sort) ? ($max_sort + 1) : 0;
        echo $next_sort;
        exit;
    }

} catch (PDOException $e) {
    $_SESSION['error'] = '操作失败：' . $e->getMessage();
}

// 获取商品列表
$products = $pdo->query("SELECT * FROM products ORDER BY sort_order ASC, id DESC")->fetchAll();

// 获取会话消息
$error = $_SESSION['error'] ?? '';
$success = $_SESSION['success'] ?? '';
unset($_SESSION['error'], $_SESSION['success']);
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title']); ?> - 商品管理</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
    <link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
    <style>
    @media (max-width: 767.98px) {
        .table-product-mobile {
            display: block;
            width: 100%;
        }
        .table-product-mobile thead { display: none; }
        .table-product-mobile tbody { display: block; }
        .table-product-mobile tr { display: block; margin-bottom: 1rem; border: 1px solid #eee; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.03); background: #fff; }
        .table-product-mobile td { display: flex; width: 100%; border: none; border-bottom: 1px solid #f2f2f2; align-items: center; padding: 0.5rem 1rem; font-size: 15px; }
        .table-product-mobile td:last-child { border-bottom: none; }
        .table-product-mobile .product-label { min-width: 80px; color: #888; font-size: 13px; margin-right: 8px; display: inline-block; }
        .table-product-mobile .product-actions { justify-content: flex-end; }
    }
    @media (min-width: 768px) {
        .table-product-mobile .product-label { display: none !important; }
    }
    </style>
</head>

<body>
<div id="lyear-preloader" class="loading">
    <div class="ctn-preloader"><div class="round_spinner"><div class="spinner"></div><img src="../assets/images/loading-logo.png" alt=""></div></div>
</div>

<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <?php $current_page = 'product_manage'; include 'navbar.php'; ?>
        
        <main class="lyear-layout-content">
            <div class="container-fluid p-t-15">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between">
                                <h4>商品管理</h4>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#productModal" onclick="prepareAdd()">
                                    <i class="mdi mdi-plus"></i> 添加商品
                                </button>
                            </div>
                            <div class="card-body">
                                <?php if ($error): ?>
                                <div class="alert alert-danger" role="alert"><?php echo $error; ?></div>
                                <?php endif; ?>
                                <?php if ($success): ?>
                                <div class="alert alert-success" role="alert"><?php echo $success; ?></div>
                                <?php endif; ?>

                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover table-product-mobile">
                                        <thead>
                                            <tr>
                                                <th>排序</th>
                                                <th>商品名</th>
                                                <th>价格</th>
                                                <th>时长</th>
                                                <th>状态</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $type_map = [
                                                'minute' => '分钟',
                                                'hour' => '小时',
                                                'day' => '天',
                                                'week' => '周',
                                                'month' => '月',
                                                'season' => '季',
                                                'quarter' => '季',
                                                'year' => '年',
                                                'forever' => '永久',
                                                // 兼容中文本身
                                                '分钟' => '分钟',
                                                '小时' => '小时',
                                                '天' => '天',
                                                '周' => '周',
                                                '月' => '月',
                                                '季' => '季',
                                                '年' => '年',
                                                '永久' => '永久'
                                            ];
                                            ?>
                                            <?php foreach ($products as $product): ?>
                                            <tr>
                                                <td><span class="product-label">排序</span><?php echo $product['sort_order']; ?></td>
                                                <td><span class="product-label">商品名</span><?php echo htmlspecialchars($product['name']); ?></td>
                                                <td><span class="product-label">价格</span>￥<?php echo number_format($product['price'], 2); ?></td>
                                                <td><span class="product-label">时长</span>
                                                    <?php
                                                    $type = $type_map[$product['duration_type']] ?? $product['duration_type'];
                                                    if ($type === '永久') {
                                                        echo '永久';
                                                    } else {
                                                        echo $product['duration_value'] . $type;
                                                    }
                                                    ?>
                                                </td>
                                                <td><span class="product-label">状态</span>
                                                    <?php if ($product['status'] == 1): ?>
                                                    <span class="badge bg-success">上架中</span>
                                                    <?php else: ?>
                                                    <span class="badge bg-danger">已下架</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="product-actions">
                                                    <form method="post" action="product_manage.php" style="display:inline-block;">
                                                        <input type="hidden" name="toggle_id" value="<?php echo $product['id']; ?>">
                                                        <button type="submit" class="btn btn-sm <?php echo $product['status']==1?'btn-warning':'btn-success'; ?>">
                                                            <?php echo $product['status']==1?'下架':'上架'; ?>
                                                        </button>
                                                    </form>
                                                    <button class="btn btn-sm btn-primary" onclick='prepareEdit(<?php echo json_encode($product); ?>)'>编辑</button>
                                                    <a href="?action=delete&id=<?php echo $product['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('确定要删除吗？')">删除</a>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- 商品模态框 -->
<div class="modal fade" id="productModal" tabindex="-1" aria-labelledby="productModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="productModalLabel">编辑商品</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form action="product_manage.php" method="post">
        <div class="modal-body">
            <input type="hidden" name="id" id="product-id">
            <input type="hidden" id="duration_type_hidden" name="duration_type">
            <div class="mb-3">
                <label for="product-name" class="form-label">商品名称</label>
                <select class="form-select" id="product-name" name="name" required>
                    <option value="">请选择类型</option>
                    <option value="分钟卡">分钟卡</option>
                    <option value="小时卡">小时卡</option>
                    <option value="天卡">天卡</option>
                    <option value="周卡">周卡</option>
                    <option value="月卡">月卡</option>
                    <option value="季卡">季卡</option>
                    <option value="年卡">年卡</option>
                    <option value="永久卡">永久卡</option>
                </select>
            </div>
            <div class="mb-3" id="sort-order-group">
                <label for="product-sort-order" class="form-label w-100">排序</label>
                <input type="number" class="form-control mt-1" id="product-sort-order" name="sort_order" value="0">
                <small class="text-muted">数字越小，排序越靠前</small>
            </div>
            <div id="product-fields" style="display:none;">
                <div class="row" id="price-row">
                    <div class="col-12 col-md-6 mb-3" id="price-group">
                        <label for="product-price" class="form-label w-100">价格 (元)</label>
                        <input type="number" class="form-control mt-1" id="product-price" name="price" step="0.01" min="0.01" required placeholder="最低设置0.01元">
                    </div>
                    <div class="col-12 col-md-6 mb-3 d-none" id="duration-value-group">
                        <label for="product-duration-value" class="form-label w-100">时长值</label>
                        <input type="number" class="form-control mt-1" id="product-duration-value" name="duration_value" min="0" required placeholder="最大59">
                    </div>
                </div>
                <div class="row" id="purchase-limit-row">
                    <div class="col-12 mb-3" id="purchase-limit-group">
                        <label for="product-purchase-limit" class="form-label w-100">购买限制</label>
                        <input type="number" class="form-control mt-1" id="product-purchase-limit" name="purchase_limit" min="0" value="0" placeholder="0为不限">
                        <small class="text-muted">每用户最多购买次数</small>
                    </div>
                </div>
            </div>
            <!-- 商品描述隐藏域 -->
            <input type="hidden" class="form-control" id="product-description" name="description">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
          <button type="submit" class="btn btn-primary">保存</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript" src="../assets/js/popper.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/perfect-scrollbar.min.js"></script>
<script type="text/javascript" src="../assets/js/main.min.js"></script>
<script>
 
const nameTypeMap = {
    '分钟卡': 'minute',
    '小时卡': 'hour',
    '天卡': 'day',
    '周卡': 'week',
    '月卡': 'month',
    '季卡': 'season',
    '年卡': 'year',
    '永久卡': 'forever'
};

const typeTextMap = {
    'minute': '分钟',
    'hour': '小时',
    'day': '天',
    'week': '周',
    'month': '月',
    'season': '季',
    'year': '年',
    'forever': '永久'
};
function getDescText() {
    var name = $('#product-name').val();
    var durationType = $('#product-duration-type').val();
    var durationValue = $('#product-duration-value').val();
    if(name === '永久卡' || durationType === 'forever') {
        return '永久使用时长';
    }
    var typeText = typeTextMap[durationType] || '';
    return durationValue + typeText + '使用时长';
}
function syncTypeByName() {
    var name = $('#product-name').val();
    if (!name) {
        $('#product-fields').hide();
        return;
    } else {
        $('#product-fields').show();
    }
    var type = nameTypeMap[name];
    $('#product-duration-type').val(type);
    $('#duration_type_hidden').val(type);
    // 动态设置时长值最大值和placeholder
    var maxValue = 9999;
    var placeholder = '';
    switch(type) {
        case 'minute': maxValue = 59; placeholder = '最大范围1-59'; break;
        case 'hour': maxValue = 23; placeholder = '最大范围1-23'; break;
        case 'day': maxValue = 30; placeholder = '最大范围1-30'; break;
        case 'week': maxValue = 4; placeholder = '最大范围1-4'; break;
        case 'month': maxValue = 11; placeholder = '最大范围1-11'; break;
        case 'season': maxValue = 3; placeholder = '最大范围1-3'; break;
        case 'year': maxValue = 9999; placeholder = '不限'; break;
        case 'forever': maxValue = 0; placeholder = ''; break;
    }
    if(type === 'forever' || type === '永久') {
        $('#productModal').find('#duration-value-group').hide().addClass('d-none');
        $('#product-duration-value').val('0');
        $('#product-duration-value').attr('min', 0);
        // 永久卡时价格和购买限制并列
        $('#price-group').removeClass('col-12 col-md-6').addClass('col-12 col-md-6');
        $('#purchase-limit-group').removeClass('col-12 mb-3').addClass('col-12 col-md-6 mb-3');
        $('#purchase-limit-row').addClass('row').removeClass('');
        $('#price-row').addClass('row').removeClass('');
        $('#purchase-limit-group').appendTo('#price-row');
    } else {
        $('#productModal').find('#duration-value-group').show().removeClass('d-none');
        if(!$('#product-duration-value').val()) {
            $('#product-duration-value').val('');
        }
        $('#product-duration-value').attr('max', maxValue);
        $('#product-duration-value').attr('min', 1);
        $('#product-duration-value').attr('placeholder', placeholder);
        // 价格和时长并列，购买限制单独一行
        $('#price-group').removeClass('col-12 col-md-6').addClass('col-12 col-md-6');
        $('#duration-value-group').removeClass('col-12 col-md-6').addClass('col-12 col-md-6');
        $('#purchase-limit-group').removeClass('col-12 col-md-6 mb-3').addClass('col-12 mb-3');
        $('#purchase-limit-group').appendTo('#purchase-limit-row');
        $('#price-row').addClass('row').removeClass('');
        $('#purchase-limit-row').addClass('row').removeClass('');
    }
    $('#product-description').val(getDescText());
}
function prepareAdd() {
    $('#productModalLabel').text('添加商品');
    $('#product-id').val('');
    $('#product-name').val('');
    $('#product-fields').hide();
    $('#product-duration-value').val('');
    $('#product-price').val('');
    $('#product-purchase-limit').val('0');
    // 获取下一个排序值
    $.get('product_manage.php?action=next_sort', function(data) {
        $('#product-sort-order').val(data);
    });
    $('#productModal').modal('show');
    $('#product-description').val('');
}
function prepareEdit(product) {
    $('#productModalLabel').text('编辑商品');
    $('#product-id').val(product.id);
    $('#product-name').val(product.name);
    $('#product-duration-value').val(product.duration_value);
    $('#product-price').val(product.price);
    $('#product-sort-order').val(product.sort_order);
    $('#product-purchase-limit').val(product.purchase_limit || 0);
    $('#productModal').modal('show');
    $('#product-description').val(getDescText());
}
// 弹窗真正显示后再同步隐藏时长值输入框
$('#productModal').on('shown.bs.modal', function () {
    syncTypeByName();
});
$('#product-name').on('change', function() {
    syncTypeByName();
    $('#product-description').val(getDescText());
});
$('#product-duration-value').on('input change', function() {
    $('#product-description').val(getDescText());
});
</script>
</body>
</html> 